<template>
  <div class="app-container">
    <template>
      <el-row>
        <el-col :span="24">
          <div class="h_top">
            <div class="search_box">
              <el-form :model="query" :inline="true">
                <el-row :gutter="10">
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">编 号</div>
                      <el-input v-model="query.coding" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">名 称</div>
                      <el-input v-model="query.name" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">资 产</div>
                      <v-select-s v-model="query.equipment_id" action="eqList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">车 间</div>
                      <el-select v-model="query.workshop" size="mini">
                        <el-option v-for="(item,workshopIndex) in planWorkshop" :key="workshopIndex" :label="item" :value="workshopIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">优先程度</div>
                      <el-select v-model="query.priority" size="mini">
                        <el-option v-for="(item,priorityIndex) in priority" :key="priorityIndex" :label="item" :value="priorityIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">专 业</div>
                      <el-select v-model="query.profession" size="mini">
                        <el-option v-for="(item,professionIndex) in profession" :key="professionIndex" :label="item" :value="professionIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">周 期</div>
                      <el-input v-model="query.period" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">负责人</div>
                      <v-select-s v-model="query.admin_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">类 型</div>
                      <el-select v-model="query.type" size="mini">
                        <el-option v-for="(item, typeIndex) in typeCategory" :key="typeIndex" :value="typeIndex" :label="item" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">状 态</div>
                      <el-select v-model="query.status" size="mini">
                        <el-option v-for="(item, commonIndex) in commonStatus" :key="commonIndex" :label="item" :value="commonIndex" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">准备（天数）</div>
                      <el-input v-model="query.ready" size="mini" @keyup.enter.native="search" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">操作者</div>
                      <v-select-s v-model="query.query_admin_id" action="adminList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">生产线</div>
                      <v-select-s v-model="query.line_id" action="lineList" />
                    </el-form-item>
                  </el-col>
                  <el-col :xl="2" :lg="3">
                    <el-form-item>
                      <div class="search_label">工位</div>
                      <v-select-s v-model="query.process" action="processList" multiple :query="{line_id:query.line_id}" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="2">
                    <el-form-item>
                      <div class="search_label">操 作</div>
                      <el-button type="primary" icon="el-icon-search" size="mini" @click="search">查找</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <div class="toolBars">
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-document-add" size="mini" @click="addHandler">增加</el-button>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-printer" size="mini" @click="dialogTableVisible = true">导出</el-button>
                <el-dialog title="设备资产导出" :visible.sync="dialogTableVisible" width="45%" center>
                  <el-checkbox v-model="checkAll" class="marginLeft20" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
                  <el-checkbox-group v-model="needExport" class="marginLeft20" @change="handleText">
                    <el-checkbox v-for="item in needExportArray" :key="item" class="width73" checked :label="item">{{ item }}</el-checkbox>
                  </el-checkbox-group>
                  <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogTableVisible = false">取 消</el-button>
                    <el-button type="primary" @click="exportHandler">确 定</el-button>
                  </div>
                </el-dialog>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbook">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量新增</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-upload :show-file-list="false" action="" :before-upload="workbookUpdate">
                  <el-button type="primary" size="mini" icon="el-icon-upload">批量更新</el-button>
                </el-upload>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-delete" :disabled="!selection.length" size="mini" @click="remove">删除</el-button>
              </div>
              <div class="buttonBox">
                <a class="download" href="https://beiqi.aiemtc.com/exl/plan4.xlsx" download="" title="下载"><el-button type="primary" icon="el-icon-download" size="mini">下载模板</el-button></a>
              </div>
              <div class="buttonBox">
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="reloadHandler">刷新</el-button>
              </div>
              <div class="fr">总计划数：<span>{{ total }}</span>，总设备数：<span>{{ eqs }}</span>，总任务项：<span>{{ tasks }}</span></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </template>
    <div>
      <el-table v-loading="loading" :data="planList" size="small" stripe border :header-cell-style="{background:'#eef1f6',color:'#606266'}" style="width: 100%" @selection-change="selectionHandler">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="coding" label="编号" width="150" align="center" />
        <el-table-column label="名称" width="250">
          <template scope="scope">
            {{ scope.row.eq.coding }}-{{ scope.row.eq.name }}
          </template>
        </el-table-column>
        <el-table-column prop="eq.workshop_name.name" label="车间" align="center" width="130" />
        <el-table-column prop="eq.line_name.name" label="生产线" align="center" width="130" />
        <el-table-column prop="type" label="类别" width="" align="center" :formatter="typeFormat" />
        <el-table-column prop="admin.name" label="负责人" width="100" align="center" />
        <el-table-column prop="members" label="操作者" width="100" align="center" />
        <el-table-column prop="execute_date" label="下一个日期" width="200" align="center" />
        <el-table-column prop="period" label="周期" width="120" align="center" :formatter="periodFormat" />
        <el-table-column prop="status" label="状态" width="120" align="center" :formatter="statusFormat" />
        <el-table-column prop="approve" label="审批" width="120" align="center" :formatter="approveFormat" />
        <el-table-column v-if="listHandle" fixed="right" label="操作" width="150" align="center">
          <template scope="scope">
            <el-button type="primary" size="mini" @click="updateHandler(scope.row.id)">编辑</el-button>
            <div hidden>
              <el-button size="mini" type="danger" @click="confirmDel(scope.row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="page" background :page-size="query.limit" layout="total,prev,pager,next,jumper" :total="total" :current-page.sync="query.page" @current-change="index" @size-change="index" />
    </div>
  </div>
</template>
<script>
import API from '@/api/project/plan4'
import { profession, priority, commonStatus, typeCategory, planWorkshop } from '@/utils/options'
import VSelectS from '@/components/select-search'
import xlsx from 'xlsx'
import exportMethod from '@/mixins/export'
export default {
  inject: ['reload', 'goUrl', 'delOne', 'delMany', 'getPlanStatusFormat', 'getApproveStatusFormat', 'formatDate', 'getPlanTypeFormat', 'getPlanPeriodFormat', 'getScope'],
  components: {
    VSelectS
  },
  mixins: [exportMethod],
  data() {
    return {
      loading: false,
      total: 0,
      eqs: 0,
      tasks: 0,
      query: { page: 1, limit: 15 },
      planList: [],
      selection: [],
      profession,
      priority,
      commonStatus,
      typeCategory,
      planWorkshop
    }
  },
  computed: {
    tableMaxHeight() {
      return window.innerHeight - 260 + 'px'
    },
    listHandle() {
      return this.$store.state.settings.listHandle
    }
  },
  created() {
    const query = JSON.parse(sessionStorage.getItem('query'))
    if (query) {
      this.query = query
      sessionStorage.removeItem('query')
    }
    this.index()
  },
  methods: {
    search() {
      this.query.page = 1
      this.index()
    },
    selectionHandler(selection) {
      this.selection = selection
    },
    index() {
      this.loading = true
      const _this = this
      API.planList(this.query).then(response => {
        this.total = response.data.res.total
        this.eqs = response.data.eqs
        this.tasks = response.data.tasks

        response.data.res.data.forEach(function(e) {
          const execute_date = e.execute_date
          const period = e.period
          const next_date = new Date(execute_date).getTime() + period * 24 * 3600 * 1000
          e.next_date = _this.formatDate(next_date)
        })

        this.planList = response.data.res.data
        if (this.planList && this.planList.length) {
          this.planList.forEach(item => {
            const om = []
            item.other_member.map(i => {
              if (i.admin) {
                om.push(i.admin.name)
              } else {
                om.push('删除')
              }
            })
            item.members = om.join(',')
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    exportHandler() {
      const data = [
        [
          '编号',
          '名称',
          '单位',
          '资产',
          '优先程度',
          '专业',
          '执行时间',
          '周期',
          '成本代码',
          '负责人',
          '类型',
          '状态',
          '准备（天数）',
          '验证人员',
          '验证时间',
          '排序'
        ]
      ]
      let priority = ''
      let profession = ''
      let type = ''
      let status = ''
      let v_name = ''
      let v_date = ''

      if (this.selection.length === 0) {
        this.$message.error('请选择要到导出的数据')
        return false
      } else {
        this.selection.forEach((item) => {
          if (item.priority === 0) {
            priority = '所有'
          } else if (item.priority === 1) {
            priority = '48小时内'
          } else if (item.priority === 2) {
            priority = '超过48小时'
          } else if (item.priority === 3) {
            priority = '立即'
          }

          if (item.profession === 0) {
            profession = '所有'
          } else if (item.profession === 1) {
            profession = '电气'
          } else if (item.profession === 2) {
            profession = '机械'
          }

          if (item.type === 0) {
            type = '系统'
          } else {
            type = '自定义'
          }

          if (item.status === 0) {
            status = '启用'
          } else if (item.status === 1) {
            status = '停用'
          }
          if (item.verify_admin) {
            v_name = item.verify_admin.name
            v_date = item.verify_date
          } else {
            v_name = '未审核'
            v_date = '未审核'
          }

          data.push([
            item.coding,
            item.name,
            item.unit,
            item.eq.name,
            priority,
            profession,
            item.execute_date,
            item.period,
            item.cost.coding,
            item.admin.name,
            type,
            status,
            item.ready,
            v_name,
            v_date,
            item.sort
          ])
        })
      }
      const workbook = {
        SheetNames: ['projectPlan'],
        Sheets: {
          'projectPlan': xlsx.utils.aoa_to_sheet(data)
        }
      }
      this.exportExec(workbook, '更新维护计划数据报表.xlsx')
    },
    remove() {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const selection = this.selection
      const ids = selection
        .map((item) => {
          return item.id
        })
        .join(',')
      this.$confirm('要同步删除跟该计划相关的工单吗（已归档的工单无影响）?', '提示', {
        confirmButtonText: '同步',
        cancelButtonText: '不同步',
        type: 'warning'
      }).then(() => {
        API.delete({ id: ids, together: 'yes' }).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.reload()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {
        API.delete({ id: ids, together: 'no' }).then((response) => {
          if (response.data.error_code === 1) {
            this.$message({
              message: '恭喜你，删除成功',
              type: 'success'
            })
            this.reload()
          } else {
            this.$message.error(response.data.message)
          }
        })
      })
    },
    confirmDel(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      this.delOne(API, id, false)
    },
    priorityFormat(row) {
      return this.getPlanProfessionFormat(row)
    },
    typeFormat(row) {
      return this.getPlanTypeFormat(row)
    },
    professionFormat(row) {
      return this.getPlanProfessionFormat(row)
    },
    periodFormat(row) {
      return this.getPlanPeriodFormat(row)
    },
    addHandler() {
      this.goUrl('/project/plan4/plan_add')
    },
    updateHandler(id) {
      sessionStorage.setItem('query', JSON.stringify(this.query))
      const url = `/project/plan4/plan_edit/${id}`
      this.goUrl(url)
    },
    reloadHandler() {
      this.reload()
    },
    statusFormat(row) {
      return this.getCommonStatusFormat(row)
    },
    approveFormat(row) {
      return this.getApproveStatusFormat(row)
    },
    workbook(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excel(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，导入成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    },
    workbookUpdate(file) {
      const reader = new FileReader()
      const _this = this
      reader.onload = function(e) {
        let outData = []
        const data = e.target.result
        const workbook = xlsx.read(data, { type: 'binary' })
        const sheetNames = workbook.SheetNames
        sheetNames.forEach(() => {
          outData = xlsx.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
        })
        API.excelUpdate(outData).then(response => {
          if (response.data.error_code === 1) {
            _this.$message.success('恭喜你，更新成功')
            _this.reload()
          } else {
            _this.$message.error(response.data.message)
          }
        })
      }
      reader.readAsBinaryString(file)
      return false
    }
  }
}
</script>
